package com.fancy.learncenter.activity;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.MaterialDetailDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.WXShareUtil;
import com.fancy.learncenter.view.PopupWindowShare;
import com.superservice.lya.R;
import com.yixia.camera.util.Log;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class NewsH5Activity extends BaseActivity {

    public static String URL_KEY = "URL_KEY";
    WebSettings mWebSettings;
//    TextView beginLoading,endLoading,loading,mtitle;

    String topLineId = "";

    String urlPath;
    @Bind(R.id.webView)
    WebView mWebview;
    @Bind(R.id.rootView)
    LinearLayout rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_h5, getResources().getColor(R.color.toolbar_color));
        ButterKnife.bind(this);
        initToolbar("");
        setRightImg(R.mipmap.ic_fenxiang, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindowShare == null) {
                    popupWindowShare = new PopupWindowShare(NewsH5Activity.this, rootView);
                    popupWindowShare.setOnClickCallBack(new PopupWindowShare.OnClickCallBack() {
                        @Override
                        public void wxFriendCallBack() {
                            WXShareUtil.getInstance(NewsH5Activity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, true);
                        }

                        @Override
                        public void wxCallBack() {
                            WXShareUtil.getInstance(NewsH5Activity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, false);
                        }
                    });
                }
                popupWindowShare.showAtLocation();

            }
        });

        mWebSettings = mWebview.getSettings();


        urlPath = getIntent().getStringExtra(URL_KEY);
        topLineId = getIntent().getStringExtra("topLineId");

//        urlPath="http://yigoutong.shweijue.com//index.php/wx/topLine/skipdetail/id/1";


//        urlPath="https://www.baidu.com/?tn=98050039_dg&ch=1";
        getAccount();

        mWebview.loadUrl(urlPathgetLoadUrl(urlPath));


        //支持JS
        mWebview.getSettings().setJavaScriptEnabled(true);
        //设置可访问文件
        mWebSettings.setAllowFileAccess(true);
        //设置适应屏幕
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        //支持缩放
        mWebSettings.setSupportZoom(false);
        //隐藏原生的缩放控件
        mWebSettings.setDisplayZoomControls(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //   设置缓存模式
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setDomStorageEnabled(true);//开启DOM缓存
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebSettings.setAppCachePath(mWebview.getContext().getCacheDir().getAbsolutePath());

        //支持自动加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            mWebSettings.setLoadsImagesAutomatically(true);
        } else {
            mWebSettings.setLoadsImagesAutomatically(false);
        }

        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setBuiltInZoomControls(true);
        //设置不用系统浏览器打开,直接显示在当前Webview
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        //设置WebChromeClient类
        mWebview.setWebChromeClient(new WebChromeClient() {


            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                System.out.println("标题在这里");
//                mtitle.setText(title);

                setTitle(title);
            }


            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
//                if (newProgress < 100) {
//                    String progress = newProgress + "%";
//                    loading.setText(progress);
//                } else if (newProgress == 100) {
//                    String progress = newProgress + "%";
//                    loading.setText(progress);
//                }
            }
        });


        //设置WebViewClient类
        mWebview.setWebViewClient(new WebViewClient() {
            //设置加载前的函数
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                System.out.println("开始加载了");
//                beginLoading.setText("开始加载了");

            }

            //设置结束加载函数
            @Override
            public void onPageFinished(WebView view, String url) {
//                endLoading.setText("结束加载了");

            }
        });
    }

    @Override
    public void finish() {
        mWebview.post(new Runnable() {
            @Override
            public void run() {
                mWebview.loadUrl("about:blank");
            }
        });
        super.finish();
    }

    //点击返回上一页面而不是退出浏览器
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
//            mWebview.goBack();
//            return true;
//        }

        return super.onKeyDown(keyCode, event);
    }

    //销毁Webview
    @Override
    protected void onDestroy() {
        if (mWebview != null) {
            mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebview.clearHistory();

            ((ViewGroup) mWebview.getParent()).removeView(mWebview);
            mWebview.destroy();
            mWebview = null;
        }
        super.onDestroy();
    }


    private String urlPathgetLoadUrl(String url, String banner_id) {

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        if (sbUrl.toString().contains("?")) {
            if (sbUrl.toString().contains("fromapp_user_id=")) {

            } else {
                sbUrl.append("&fromapp_user_id=" + MyApplication.userId).append("&banner_id=" + banner_id);
            }
        } else {
            sbUrl.append("?fromapp_user_id=" + MyApplication.userId).append("&banner_id=" + banner_id);
        }
        return sbUrl.toString();
    }

    private String urlPathgetLoadUrl(String url) {

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        if (sbUrl.toString().contains("?")) {
            if (sbUrl.toString().contains("fromapp_user_id=")) {

            } else {
                sbUrl.append("&fromapp_user_id=" + MyApplication.userId);
            }
        } else {
            sbUrl.append("?fromapp_user_id=" + MyApplication.userId);
        }
        return sbUrl.toString();
    }


    PopupWindowShare popupWindowShare;

    String shareUrlPic = "";
    String shareLinkUrl = "";
    String shareTitle = "";
    String shareContent = "";


    private void getAccount() {
        Map maps = new HashMap();
        maps.put("topLineId", topLineId);
        HttpMehtod.getInstance().topLineDataDetail(maps, new IdeaObserver<BaseDataBean<MaterialDetailDataBean>>(this, true) {

            @Override
            public void onSuccess(BaseDataBean<MaterialDetailDataBean> listBaseDataBean) {


                shareUrlPic = listBaseDataBean.getData().getShare_img();
                shareContent = listBaseDataBean.getData().getShare_content();

                shareLinkUrl = urlPathgetLoadUrl(listBaseDataBean.getData().getShare_link(), listBaseDataBean.getData().getBanner_id());
                shareTitle = listBaseDataBean.getData().getShare_title();

            }

            @Override
            public void onFail(int errorCode) {

            }

        });
    }


}
